/*!
 * js公共库
 * Date: 2015-03-20 13:57
 */
//对象转字符串
function obj2str(o) {
    var r = [];
    if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
    if (typeof o == "object") {
        if (!o.sort) {
            for (var i in o)
                r.push(i + ":" + obj2str(o[i]));
            if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
                r.push("toString:" + o.toString.toString());
            }
            r = "{" + r.join() + "}";
        } else {
            for (var i = 0; i < o.length; i++)
                r.push(obj2str(o[i]));
            r = "[" + r.join() + "]";
        }
        return r;
    }
    return o.toString();
}
String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
}

String.prototype.endWith = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
}
//日期格式化
Date.prototype.toJSON = function () {
    return this.getTime();
};
Date.prototype.format = function (patten) {
    if (!this || !this.getTime) return "";
    var _patten = patten || "yyyy-MM-dd";
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(_patten)) {
        _patten = _patten.replace(RegExp.$1, (this.getFullYear() + "")
            .substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(_patten)) {
            _patten = _patten.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return _patten;
}
//表单序列化为对象
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        o[this.name] = this.value || '';
    });
    return o;
};
//检查长度设置
function checkLength(str, length) {
    if (typeof str == "string" && typeof length == "number") {
        if (str.length > length)
            str = str.substring(0, length) + "…";
        return str;
    } else {
        return "";
    }

}
//值替换
function valueReplace(v) {
    v = v.toString().replace(new RegExp('(["\'"])', 'g'), "\\\'");
    return v;
}
//ajax部分
$.ajaxSetup({
    cache: false,
    type: "POST",
    error: function (a, b, c) {
    }
});
//严格脚本检查。
function stripscript(s) {
    var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");
    /**
     var rs = "";
     for (var i = 0; i < s.length; i++) {
		rs = rs+s.substr(i, 1).replace(pattern, '');
	}*/
    return !pattern.test(s);
}
//日期是否合法
function isDate(s) {
    var regexp = /^([1][7-9][0-9][0-9]|[2][0][0-9][0-9])(\-)([0][1-9]|[1][0-2])(\-)([0-2][1-9]|[3][0-1])(\s([0-1][0-9]|[2][0-3])(:)([0-5][0-9])(:)([0-5][0-9]))?$/g;
    return regexp.test(s);
}
//消除字符串左右空格
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
//货币验证。
function isDollar(s) {
    var regexp = /^(([1-9]{1})(\d+)(\.{0,1}\d{0,2})|(0{1})(\.\d\d){0,1})$/g;
    return regexp.test(s);
}

/**
 * 检查是否是IE6
 * @returns {Boolean}
 */
function checkIsIe6() {
    var flag = false;
    var browser = navigator.appName;
    if (browser != "Netscape") {
        var b_version = navigator.appVersion;
        var version = b_version.split(";");
        var trim_Version = version[1].replace(/[ ]/g, "");
        if (browser == "Microsoft Internet Explorer" && trim_Version == "MSIE6.0") {
            flag = true;
        }
    }
    return flag;
}

!(function ($) {
    "use strict";

    function findTops(list, idFuc, pIdFuc) {
        var tops = [];
        for (var i = 0, l = list.length; i < l; i++) {
            if (!pIdFuc(list[i])) {
                tops.push(list[i]);
            } else {
                var find = false;
                for (var j = 0, k = list.length; j < k; j++) {
                    if (i == j) {
                        continue;
                    }
                    find = pIdFuc(list[i]) == idFuc(list[j]);
                    if (find) {
                        break;
                    }
                }
                if (!find) {
                    tops.push(list[i]);
                }
            }
        }
        return tops;
    }

    function _group(_tops, list, idFuc, pIdFuc) {
        for (var i = 0, l = _tops.length; i < l; i++) {
            for (var j = 0, k = list.length; j < k; j++) {
//                if (i == j) {
//                    continue;
//                }
                if (pIdFuc(list[j]) == idFuc(_tops[i])) {
                    if (!_tops[i].children) {
                        _tops[i].children = [];
                    }
                    _tops[i].children.push(list[j]);
                    _group([list[j]], list, idFuc, pIdFuc);
                }
            }
        }
    }


    $.utils = {
        cache: {
            ajaxCache: 0,
            ajaxSuccess: 0
        },
        isJson: function (obj) {
            return obj && typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
        },
        setAccessor: function (expr, value, root) {
            root = root || {};
            if (!expr || typeof expr === 'function') {
                return root;
            }
            var ar = expr.split(".");
            _set(value, root);
            function _set(vl, obj) {
                var _obj = obj[ar[0]] || {};
                _obj = $.utils.isJson(_obj) ? _obj : {};
                if (ar.length == 1) {
                    _obj = vl;
                    obj[ar[0]] = _obj;
                } else {
                    obj[ar[0]] = _obj;
                    ar = ar.slice(1);
                    obj = obj[ar[0]];
                    _set(vl, _obj);
                }
            }

            return root;
        },
        getAccessor: function (obj, expr) {
            var ret, p, prm = [], i;
            if (typeof expr === 'function') {
                return expr(obj);
            }
            ret = obj[expr];
            if (ret === undefined) {
                try {
                    if (typeof expr === 'string') {
                        prm = expr.split('.');
                    }
                    i = prm.length;
                    if (i) {
                        ret = obj;
                        while (ret && i--) {
                            p = prm.shift();
                            ret = ret[p];
                        }
                    }
                } catch (e) {
                }
            }
            return ret == null || ret == "null" ? "" : ret;
        },
        buildJson: function (params, prex) {
            var json = {};
            //第一次便利去掉空的
            function buildPrams(prex, _params) {
                if (!$.utils.isJson(_params)) {
                    var length = prex.length;
                    var __prex = prex;
                    if (prex.charAt(prex.length - 1) == '.') {
                        __prex = prex.substr(0, length - 1);
                    }
                    json[__prex] = _params;
                } else
                    for (var i in _params) {
                        var data = _params[i];
                        var _va = prex;
                        if (prex && prex.charAt(prex.length - 1) != '.') {
                            _va += ".";
                        }
                        if (data !== undefined && data !== null) {
                            switch (typeof data) {
                                case "object":
                                    if ($.isArray(data)) {
                                        for (var j = 0; j < data.length; j++) {
                                            if (data[j] != undefined && data[j] != "")
                                                buildPrams(_va + i + "[" + j + "]" + ".", data[j]);
                                        }
                                    } else {
                                        buildPrams(_va + i + ".", data);
                                    }
                                    break;
                                case "function":
                                {
                                    //方法不进行
                                    break;
                                }
                                default:
                                    if (data != undefined && data != "")
                                        json[_va + i] = data;
                                    break;
                            }
                        }
                    }
                return json;
            }

            var _prex = prex ? prex : "";
            return buildPrams(_prex, params);
        },
        initTree: function (option) {
            var attr = option.attr ? option.attr : {id: function (data) {
                return data["id"]
            }, pId: function (data) {
                return data["parentId"]
            }};
            var list = option.data;
            var tops = findTops(list, attr.id, attr.pId);
            _group(tops, list, attr.id, attr.pId);
            return tops;
        },
        createUUID: function (len, radix) {
            var chars = '3456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''), uuid = [], i;
            radix = radix || chars.length;

            if (len) {
                // Compact form
                for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
            } else {
                // rfc4122, version 4 form
                var r;

                // rfc4122 requires these characters
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';

                // Fill in random data.  At i==19 set the high bits of clock sequence as
                // per rfc4122, sec. 4.1.5
                for (i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random() * 16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }
            return uuid.join('');
        },
        loadAttribute: function (collections, func, operate) {
            var _collect = [];
            for (var i = 0, len = collections.length; i < len; i++) {
                _collect.push(func(collections[i]))
            }
            return operate ? operate(_collect) : _collect;
        },
        cutWord: function (src, length, endString) {
            if (!src) {
                return "";
            }
            if (src.length < length) {
                return src;
            }
            return src.substr(0, length) + endString;
        },
        loadCookie: function (key) {
            var cookie = document.cookie;
            cookie = cookie.split(";");
            for (var i = 0, len = cookie.length; i < len; i++) {
                var _1 = cookie[i];
                var _2 = _1.indexOf("=");
                if ($.trim(_1.substr(0, _2)) == key) {
                    return _1.substr(_2 + 1);
                }
            }
            return "";
        },
        commonBase64: {
            encode: function (input, arg) {
                var output = "";
                var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
                var i = 0;
                input = $.commonBase64._utf8_encode(input + "_" + arg);
                while (i < input.length) {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);
                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;
                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    } else if (isNaN(chr3)) {
                        enc4 = 64;
                    }
                    output = output +
                        $.utils.commonBase64._keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
                        $.utils.commonBase64._keyStr.charAt(enc3) + _keyStr.charAt(enc4);
                }
                return output;
            },
            decode: function (input, arg) {
                var output = "";
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;
                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
                while (i < input.length) {
                    enc1 = _keyStr.indexOf(input.charAt(i++));
                    enc2 = _keyStr.indexOf(input.charAt(i++));
                    enc3 = _keyStr.indexOf(input.charAt(i++));
                    enc4 = _keyStr.indexOf(input.charAt(i++));
                    chr1 = (enc1 << 2) | (enc2 >> 4);
                    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                    chr3 = ((enc3 & 3) << 6) | enc4;
                    output = output + String.fromCharCode(chr1);
                    if (enc3 != 64) {
                        output = output + String.fromCharCode(chr2);
                    }
                    if (enc4 != 64) {
                        output = output + String.fromCharCode(chr3);
                    }
                }
                output = $.commonBase64._utf8_decode(output);
                return output.substring(0, output.indexOf("_") + 1);
            },
            _utf8_encode: function (string) {
                string = string.replace(/\r\n/g, "\n");
                var utftext = "";
                for (var n = 0; n < string.length; n++) {
                    var c = string.charCodeAt(n);
                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    } else if ((c > 127) && (c < 2)) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    } else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }

                }
                return utftext;
            }, _utf8_decode: function (utftext) {
                var string = "";
                var i = 0, c = 0, c1 = 0, c2 = 0, c3;
                while (i < utftext.length) {
                    c = utftext.charCodeAt(i);
                    if (c < 128) {
                        string += String.fromCharCode(c);
                        i++;
                    } else if ((c > 191) && (c < 224)) {
                        c2 = utftext.charCodeAt(i + 1);
                        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                        i += 2;
                    } else {
                        c2 = utftext.charCodeAt(i + 1);
                        c3 = utftext.charCodeAt(i + 2);
                        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                        i += 3;
                    }
                }
                return string;
            }
        }
    };

    $.EasyUiLoader = function (_95e, _95f, _960) {
        var opts = $(this).datagrid("options"), $this = $(this);
        if (!opts.url) {
            return false;
        }
        $.ajax({
            type: opts.method,
            url: opts.url,
            data: _95e,
            dataType: "json",
            success: function (data) {
                if ($.isErrorRequest(data)) {
                    $.messager.alert('数据加载失败', data.msg, 'error');
                    $this.datagrid("loaded");
                    return;
                }
                FastJson.format(data);
                _95f({
                    total: data.totalElements,
                    rows: data.content
                });
            },
            error: function () {
                _960.apply(this, arguments);
            }
        });
    }
    $.utils.isError = function (result) {
        return $.isErrorRequest(result);
    };

    $.utils.parseToJson = function (jqDom) {
        var jsons = [];
        jqDom.each(function () {
            var attrs = this.attributes, flag = false, json = {};
            for (var i = 0, l = attrs.length; i < l; i++) {
                var name = attrs[i].name;
                if (/^data/.test(name)) {
                    flag = true;
                    json[name.substr(name.indexOf("-") + 1)] = $(this).attr(name);
                }
            }
            if (flag) {
                json["icon"] = "/static/images/medal_silver.png";
                jsons.push(json);
            }
        });
        return jsons;
    };

    $.fn.serializeJson = function (method) {
        var obj = $(this);
        if(!obj.length){
            return {};
        }
        var tagName = obj[0].tagName;
        if (tagName != "FORM") {
            obj.find("textarea").each(function(){
                $(this).html($(this).val());
            });
            var hiddenForm = $("<form style='display: none'></form>").appendTo("body");
            if(tagName == "LI"){
                 obj.clone(true).appendTo(hiddenForm).wrap("<ul></ul>");
            }else if(tagName == "dd" || tagName == "dt"){
                obj.clone(true).appendTo(hiddenForm).wrap("<dl></dl>");
            }else if(tagName == "td" || tagName == "th"){
                obj.clone(true).appendTo(hiddenForm).wrap("<table><tr></tr></table>");
            }else if(tagName == "tr"){
                obj.clone(true).appendTo(hiddenForm).wrap("<table></table>");
            }else{
                obj.clone(true).appendTo(hiddenForm);
            }
            obj = hiddenForm;
        }
        var _method = method || obj.attr("method") || "GET";
        var queryArray = obj.serializeArray();
        if(tagName != "FORM"){
            obj.remove();
        }
        var json = {};
        var mutiData = {};
        for (var i = 0; i < queryArray.length; i++) {
            var value = queryArray[i].value;
            if (json[queryArray[i].name] !== undefined) {
                if (mutiData[queryArray[i].name] === undefined) {
                    mutiData[queryArray[i].name] = [value];
                } else {
                    mutiData[queryArray[i].name].push(value);
                }
            } else {
                json[queryArray[i].name] = value;
            }
        }
        for (var i in mutiData) {
            mutiData[i].unshift(json[i]);
            json[i] = mutiData[i].join(",");
        }
        return json;
    };
    function PageDomFactory(uuid) {
        var page = $("#" + uuid), that = this;
        this.factory = page.parent();
    }

    PageDomFactory.prototype.getJqDom = function (id) {
        var jqDom = this.factory.find("[data-id=" + id + "]");
        return jqDom ? jqDom : $();
    };

    PageDomFactory.prototype.getFactory = function () {
        return this.factory;
    };

    PageDomFactory.prototype.getDom = function (id) {
        return this.getJqDom(id)[0];
    };

    $.PageDomFactory = PageDomFactory

})(jQuery);

(function () {
    "use strict";

    $.fn._baseGridSelect1 = function (options, param, defaults) {
        if (typeof options == 'string') {
            return this.combogrid(options, param);
        }
        else {
            var uuid = $.utils.createUUID(6);
            var op = $.extend({server: ""}, defaults, options);
            var sear = op.form.items ? op.form.items.join('<span class="ml10"></span>') : "";
            if (sear.length) {
                sear = '<div id="' + uuid + '" style="padding:5px;height:auto"><form>' + sear + '<span class="ml10"></span>' +
                    '<a data-id="do-query" href="#" iconCls="fa fa-search fa-lg">搜索</a><span class="ml10"></span>' +
                    '<a data-id="do-queryAll" href="#" iconCls="fa fa-refresh fa-lg">搜索全部</a></form></div>';
                var context = $(sear).appendTo("body").attr("id", uuid);
                if (op.form.render) {
                    op.form.render.call(this, context, op);
                }
                var $this = $(this), root = $("#" + uuid);
                root.find("[data-id=do-query]").linkbutton({
                    onClick: function () {
                        var postData = $(this).parents("form").serializeJson();
                        $this.combogrid("grid").datagrid("reload", $.utils.buildJson(postData));
                    }
                });
                root.find("[data-id=do-queryAll]").linkbutton({
                    onClick: function () {
                        $(this).parents("form").form("reset");
                        $this.combogrid("grid").datagrid("reload", $.utils.buildJson(null));
                    }
                });
                op.toolbar = "#" + uuid;
            }
            return this.combogrid(op, param);
        }
    };

    $.fn.userSelect = function (options, param) {
        return this._baseGridSelect1(options, param, {
            panelWidth: 510,
            panelHeight: 300,
            idField: 'id',
            textField: 'userName',
            editable: false,
            multiple: false,
            url: "#",
            loader: $.EasyUiLoader,
            pagination: true,
            columns: [
                [
                    {
                        field: 'id',
                        hidden: true
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'userNumber',
                        title: '用户名',
                        width: 150,
                        align: 'center'
                    },
                    {
                        field: 'userName',
                        title: '姓名',
                        width: 150,
                        align: 'center'
                    },
                    {
                        field: 'orgsDescription',
                        title: '小组',
                        width: 150,
                        align: 'center',
                        formatter: function (value, row, index) {
                            if (!value || !value.length) {
                                return "暂无";
                            }
                            return value;
                        }
                    }
                ]
            ],
            form: {
                items: [
                    '<span class="mr10">按姓名：</span><input name="userName" class="hydra-input-width" style="width:80px" placeholder="姓名..."/>',
                    '<span class="mr10">按小组：</span><select data-id="sysOrganizations" name="orgId" class="hydra-input-width" style="width:100px"></select>'
                ],
                render: function (context, op) {
                    context.find("[data-id=sysOrganizations]").combobox({
                        url: op.organizationUrl,
                        valueField: 'id',
                        textField: 'orgName',
                        loadFilter: function (data) {
                            data.unshift({id: "", orgName: "全部"});
                            return data;
                        },
                        editable: false
                    });
                }
            }
        });
    };

    Array.prototype.contains = function (node) {
        if (!this.length) {
            return false;
        }
        for (var i = 0, l = this.length; i < l; i++) {
            if (node === this[i]) {
                return true;
            }
        }
        return false;
    };
    Array.prototype.map = function (eachFuc) {
        var nes = [];
        for (var i = 0, l = this.length; i < l; i++) {
            nes.push(eachFuc(this[i]));
        }
        return nes;
    };

    $.isErrorRequest = function (data) {
        return $.isPlainObject(data) && data.error;
    };
})(jQuery);
/**
 * 格式化展示只要年yyyy
 * @param date
 * @returns {*}
 */
function formatter2(date) {
    if (!date) {
        return '';
    }
    var y = date.getFullYear();
    return y
}
function parser2(s) {
    if (!s) {
        return null;
    }
    var y = parseInt(s, 10);
    if (!isNaN(y)) {
        return new Date(y, 1, 1);
    } else {
        return new Date();
    }
}










